package com.xiaochi.subject.infra.config;

import com.xiaochi.subject.common.context.LoginContextHolder;
import com.xiaochi.subject.common.util.LoginUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;

import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.Executors;

/**
 *
 * 填充createBy，createTime等公共字段的拦截器
 *
 * todo 手写填充拦截器
 *
 * @author zqx
 * @since 2024/9/9
 */
@Component
@Slf4j
@Intercepts({@Signature(type = Executors.class,method = "update",args = {
        MappedStatement.class,Object.class
})})
public class MybatisInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // todo Plugin就会调用这个方法
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        Object parameter = invocation.getArgs()[1];
        if (parameter == null){
            return invocation.proceed();
        }
        //获取当前登录用户的id
        String loginId = LoginUtil.getLoginId();
        if (StringUtils.isBlank(loginId)){
            //todo 就是method.invoke() 方法 相当于放行
            return invocation.proceed();
        }
        //这里面处理逻辑
        if (SqlCommandType.INSERT == sqlCommandType || SqlCommandType.UPDATE == sqlCommandType){
            replaceEntityProperty(parameter,loginId,sqlCommandType);
        }
        return invocation.proceed();
    }

    //这里替换字段
    private void replaceEntityProperty(Object parameter,String loginId,SqlCommandType sqlCommandType){
        //这里判断一下 是实体类型的 还是Map类型的
        if (parameter instanceof Map){
            replaceMap((Map) parameter, loginId, sqlCommandType);
        }else {
            replace(parameter, loginId, sqlCommandType);
        }
    }

    private void replaceMap(Map parameter ,String loginId,SqlCommandType sqlCommandType){
        for (Object val : parameter.values()){
            replace(val, loginId, sqlCommandType);
        }
    }


    //替换方法
    private void replace(Object parameter ,String loginId, SqlCommandType sqlCommandType){
        //这里判断是插入还是更新
        if (SqlCommandType.INSERT == sqlCommandType){
            dealInsert(parameter,loginId);
        }else {
            dealUpdate(parameter,loginId);
        }
    }


    private void dealUpdate(Object parameter,String loginId){
        Field[] fields = getAllFields(parameter);
        for (Field field : fields) {
            try{
                //这个是 把实体的这个字段 设置为可访问
                field.setAccessible(true);
                Object o = field.get(parameter);
                if (Objects.nonNull(o)){
                    field.setAccessible(false);
                    continue;
                }
                if ("updateBy".equals(field.getName())){
                    field.set(parameter,loginId);
                    field.setAccessible(false);
                }else if ("updateTime".equals(field.getName())){
                    field.set(parameter,new Date());
                    field.setAccessible(false);
                }else {
                    field.setAccessible(false);
                }
            }catch (Exception e){
                log.error("dealUpdate.error:{}",e.getMessage(),e);
            }

        }
    }

    //处理插入的替换字段逻辑
    private void dealInsert(Object parameter,String loginId){
        Field[] fields = getAllFields(parameter);
        for (Field field : fields) {
            try{
                //这个是把这个字段设置为可访问
                field.setAccessible(true);
                Object o = field.get(parameter);
                if (Objects.nonNull(o)){
                    field.setAccessible(false);
                    continue;
                }
                if ("isDeleted".equals(field.getName())){
                    field.set(parameter,0);
                    field.setAccessible(true);
                }else if ("createdBy".equals(field.getName())){
                    field.set(parameter,loginId);
                    field.setAccessible(false);
                }else if ("createdTime".equals(field.getName())){
                    field.set(parameter,new Date().getTime());
                    field.setAccessible(false);
                }else {
                    field.setAccessible(false);
                }
            }catch (Exception e){
                log.error("dealInsert.error:{}",e.getMessage(),e);
            }

        }
    }

    //获取到实体类的所有字段
    private Field[] getAllFields(Object object){
        Class<?> clazz = object.getClass();
        List<Field> fieldList = new ArrayList<>();
        while (clazz != null ) {
            fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
            clazz = clazz.getSuperclass();
        }
        Field[] fields = new Field[fieldList.size()];
        fieldList.toArray(fields);
        return fields;
    }

    @Override
    public Object plugin(Object target) {
        // todo 24/9/16
        // todo MyBatis 拦截器通过plugin方法创建代理对象，这里是代理对象的地方  Plugin这个类 实现了InvocationHandler接口
        // todo 可以看看Plugin这个类
        return Plugin.wrap(target,this);
    }

    @Override
    public void setProperties(Properties properties) {
    }
}
